<template>
  <div>
    <div class="lists-box">
      <div class="list_title">未开放需求申请</div>
    </div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="需求资源名称" prop="dataName">
        <el-input v-model="ruleForm.dataName" oninput="value=value.replace(/^((?!^[\u4e00-\u9fa5_a-zA-Z0-9_\s]+$).)*/g,'')"></el-input>
      </el-form-item>
      <el-form-item label="服务方式" prop="type">
        <el-radio
          v-for="(item, index) in tabsList"
          :key="index"
          v-model="ruleForm.type"
          :label="index"
          style="margin-top: 10px"
          >{{ item }}</el-radio
        >
      </el-form-item>
<!--      <el-form-item label="所属部门">-->
<!--        <treeselect v-model="selectedId" :multiple="false" :options="options"  @input="handleInput"/>-->
<!--      </el-form-item>-->
      <el-form-item label="申请部门">
        <el-input
          disabled
          v-model="parrment.dept.name"
          placeholder="法人单位名称/个人姓名"
        ></el-input>
<!--        <treeselect v-model="selectedIdSq" :multiple="false" :options="optionsSq"  @input="handleInputSq"/>-->
      </el-form-item>


<!--      <div v-if="ruleForm.type == 1">-->
<!--        <el-form-item label="出参" prop="outputArg">-->
<!--          <el-input-->
<!--            v-model="ruleForm.outputArg"-->
<!--            placeholder="服务API时填写，请求参数和返回..."-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="入参" prop="inputArg">-->
<!--          <el-input-->
<!--            v-model="ruleForm.inputArg"-->
<!--            placeholder="服务API时填写，请求参数和返回..."-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
<!--      </div>-->
      <div>
        <el-form-item label="数据项目" prop="dataItem">
          <el-input
            v-model="ruleForm.dataItem"
            placeholder="文件下载和其他类型时填写..."
          ></el-input>
        </el-form-item>
      </div>
      <el-form-item label="资源覆盖范围" prop="resourceRange">
        <el-input
          type="textarea"
          resize="none"
          :autosize="{ minRows: 3, maxRows: 4 }"
          placeholder="数据资源的地域范围、时间范围"
          v-model="ruleForm.resourceRange"
          maxlength="50"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item label="申请人">
        <el-input
          disabled
          v-model="parrment.nickName"
          placeholder="法人单位名称/个人姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="审批人" prop="spr">
        <el-select v-model="ruleForm.spr" placeholder="请选择审批人">
          <el-option
            v-for="item in sprlist"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>

<!--        <el-input-->
<!--          readonly-->
<!--          class="deptInp"-->
<!--          v-model="ruleForm.spr"-->
<!--          placeholder="审批人"-->
<!--          oninput="value=value.replace(/^((?!^[\u4e00-\u9fa5_a-zA-Z0-9_\s]+$).)*/g,'')"-->
<!--        ></el-input>-->
<!--        <div class="deptBtn">-->
<!--          <el-button @click="chooseSpr()" type="text" size="medium">-->
<!--            选择审批人-->
<!--          </el-button>-->
<!--        </div>-->
      </el-form-item>
      <div style="display: flex">
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="ruleForm.phone" placeholder="联系电话"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="联系邮箱">
          <el-input v-model="ruleForm.email" placeholder="联系邮箱"></el-input>
        </el-form-item>
      </div>
      <el-form-item label="需求描述" prop="descri">
        <el-input
          resize="none"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 4 }"
          placeholder="请输入需求描述"
          v-model="ruleForm.descri"
          maxlength="50"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <div style="display: flex">
        <el-form-item prop="startTime" label="使用起始时间">
            <el-date-picker
              :editable="false"
              type="date"
              placeholder="选择日期"
              v-model="ruleForm.startTime"
              style="width: 100%"
            ></el-date-picker>
        </el-form-item>
        <el-form-item prop="endTime" label="使用结束时间">
            <el-date-picker
              :editable="false"
              type="date"
              placeholder="选择日期"
              v-model="ruleForm.endTime"
              style="width: 100%"
            ></el-date-picker>
        </el-form-item>
      </div>
      <el-form-item label="应用场景" prop="appScene">
        <el-input
          resize="none"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 4 }"
          placeholder="请输入应用场景"
          v-model="ruleForm.appScene"
          maxlength="50"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item label="上传文件">
        <el-upload
          class="upload-demo"
          :action="xhDomain + '/api/interact/upload'"
          :on-preview="handlePreview"
          :headers="headers"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-remove="beforeRemove"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :before-upload="beforeUpload"
          :on-progress="handleProgress"
          :on-error="handleError"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </el-upload>
      </el-form-item>
<!--      <vue-editor v-model="ruleForm.cotent"></vue-editor>-->
<!--      <div v-html="contentValve" :editor-options="editorOptions"></div>-->
<!--      <el-form-item prop="code" label="验证码" style="width: 50%">-->
<!--        <el-input-->
<!--          v-model="ruleForm.code"-->
<!--          auto-complete="off"-->
<!--          placeholder="验证码"-->
<!--          style="width: 60%"-->
<!--        >-->
<!--        </el-input>-->
<!--        <div class="login-code">-->
<!--          <img :src="codeUrl" @click="getCodeFn" />-->
<!--        </div>-->
<!--      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      title="选择所属部门"
      :visible.sync="deptDialog"
      :z-index="999"
      :before-close="closeHandle"
      width="40%"
    >
      <div style="padding: 10px;margin:15px;">
        <el-table
          border
          ref="multipleTable"
          :data="deptList"
          tooltip-effect="dark"
          style="width: 100%"
          height="510"
          highlight-current-row
          @current-change="handleSelectionChange">
          <el-table-column
            label="部门名称"
            prop="name">
          </el-table-column>
          <el-table-column
            prop="parentName"
            label="上级部门">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间">
          </el-table-column>
        </el-table>
      </div>
      <div style="padding:5px 25px;">
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, sizes, jumper"
          :total="totalNum"
        >
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeHandle">取 消</el-button>
        <el-button type="primary" @click="subDeptHandle">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="选择审批人"
      :visible.sync="sprDialog"
      :z-index="999"
      :before-close="closeHandle"
    >
      <div style="padding: 10px;margin:15px;">
        <el-table
          border
          ref="multipleTable"
          :data="personalList"
          tooltip-effect="dark"
          style="width: 100%"
          height="510"
          highlight-current-row
          @current-change="handleSelSprChange">
          <el-table-column
            label="用户名称"
            prop="name"
            width="200">
          </el-table-column>
          <el-table-column
            prop="userName"
            label="账号名称"
            width="200">
          </el-table-column>
          <el-table-column
            prop="regionName"
            label="所属机构"
            show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </div>
      <div style="padding:5px 25px;">
        <el-pagination
          @size-change="sprSizeChange"
          @current-change="sprCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, sizes, jumper"
          :total="totalNum"
        >
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeHandle">取 消</el-button>
        <el-button type="primary" @click="subSprHandle">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>
<script>
import {VueEditor} from "vue2-editor";
import Quill from 'quill';
const Parchment = Quill.import('parchment');
const IndentStyle = new Parchment.Attributor.Style('textIndent', 'text-indent', {
  scope: Parchment.Scope.BLOCK,
  whitelist: ['2em', '3em']
});

Quill.register(IndentStyle, true);
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getCode, subXqData, getDept, getSpUser,getspr,getdept } from "../../../utils/httpUtils";
import {
  isvalidPhone,
  validEmail,
} from "@/utils/validate.js";
import Cookies from "js-cookie";
import Logout from "../../logout.vue";
export default {
  components: { Treeselect, VueEditor},
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const isvalidEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!validEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    const startTimeValid = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择起始时间'))
      } else {
        if (!this.ruleForm.endTime) {
          callback()
        } else if(new Date(value).getTime() < new Date(this.ruleForm.endTime).getTime()){
          callback()
        } else {
          callback(new Error('起始时间应早于结束时间'))
        }
      }
    }
    const endTimeValid = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择结束时间'))
      } else {
        if (!this.ruleForm.startTime) {
          callback()
        } else if(new Date(value).getTime() > new Date(this.ruleForm.startTime).getTime()){
          callback()
        } else {
          callback(new Error('结束时间应晚于起始时间'))
        }
      }
    }
    return {
      editorOptions: {
        modules: {
          toolbar: [
            [{ 'header': [1, 2, 3, false] }],  // 标题选项
            ['bold', 'italic', 'underline'],  // 粗体、斜体、下划线
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],  // 列表
            [{ 'textIndent': ['2em', false] }],  // 自定义的首行缩进选项
            ['clean']  // 清除格式
          ]
        }
      },
      contentValve:"",
      cotent:"",
      fileList: [],
      xhDomain:xhDomain,
      headers: { Authorization:  JSON.parse(localStorage.getItem('token')) },
      selectedId: null,  // 绑定到选中的 ID
      selectedIdSq:null,
      selectedLabel: '',  // 选中的标签
      selectedLabelSq:'',
      // define the default value
      value: null,
      // define options
      options:[],
      optionsSq:[],
      optionSq:[],
      parrment: Cookies.get("user")
        ? JSON.parse(Cookies.get("user"))
        : {},
      sprlist:[],
      sprCurrent:'',
      sprDialog:false,
      personalList:[],
      deptCurrent: '',
      deptList:[],
      totalNum:0,
      currentPage:1,
      pageSize:10,
      deptDialog:false,
      ruleForm: {
        dataName: "",//名称
        type: 0,//服务方式
        // dataDept: "",//所属部门
        // outputArg: "",//出参
        // inputArg: "",//入参
        dataItem: "",//数据项目
        resourceRange: "",//资源覆盖范围
        // sqr: "",//申请人
        spr: "",//审批人
        phone: "",//手机号
        email: "",//邮箱
        descri: "",//需求描述
        startTime: "",//使用起始时间
        endTime: "",//使用结束时间
        appScene: "",//应用场景
        code: "",//校验码
        fileId:"",//上传文件 id
      },
      sqrFlag:false,
      rules: {
        dataName: [
          { required: true, message: "请输入需求资源名称", trigger: "blur" },
          { min: 2, max: 15, message: "长度在 2 到 15 个字符", trigger: "blur" }
        ],
        dataDept: [
          { required: true, message: "请选择归属部门", trigger: "change" },
          // { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        dataItem: [
          { required: true, message: "请输入数据项", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        resourceRange: [
          { required: true, message: "请输入资源覆盖范围", trigger: "blur" },
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        email: [
          { required: true, trigger: 'blur', validator: isvalidEmail }
        ],
        appScene: [
          { required: true,  message: "请输入应用场景", trigger: "blur" },
        ],
        // sqr: [
        //   { required: true, message: "请输入申请人", trigger: "blur" },
        //   // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        // ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
        startTime: [
          { type: "date", required: true, trigger: "change", validator: startTimeValid },
        ],
        endTime: [
          { type: "date", required: true, trigger: "change", validator: endTimeValid },
        ],
      },
      tabsList: ["数据库", "服务API", "文件下载"],
      codeUrl: "",
    };
  },
  created() {
    // this.getCodeFn();
    // this.getSqr()
    this.getsprFn()
    this.getdeptFn()
  },
  methods: {
    handleError(err, file, fileList) {
      console.error('Upload error:', err, file, fileList);
      // this.uploading = false; // 隐藏进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = 'exception'; // 设置上传状态为异常
      this.$message.error('上传失败，请重试'); // 显示错误提示信息
    },
    handleProgress(event, file, fileList) {
      // this.progress = Math.round(event.percent); // 更新进度条
    },
    beforeUpload(file) {
      // this.uploading = true; // 开始上传时显示进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = ''; // 重置上传状态
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传1个文件`);
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(res, file) {
      console.log('上传成功');
      console.log(res,'res')
      this.ruleForm.fileId = res
      // 清空文件列表并重置上传组件
      // this.uploading = false; // 隐藏进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = 'success'; // 设置上传状态为成功
      // this.fileList = []; // 清空文件列表
      // this.getFileData();
    },
    handlePreview(file) {
      console.log(file,'file');
    //   文件下载
      this.$axios({
        url: xhDomain + `/api/interact/download/${file.response}`,
        method: 'post',
        responseType: 'blob', // 确保响应是二进制数据
        headers: {
          'Content-Type': 'application/json',
          "Authorization": JSON.parse(localStorage.getItem('token'))
        },
      }).then((res) => {
        console.log(res, 'res')
        const blob = new Blob([res.data], { type: 'application/octet-stream' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = file.name; // 设置下载文件的文件名，可以根据需要修改
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }, 100);
      }).catch((err) => {
        console.log(err,"err")
        // responseType: 'blob' 这个类型获取报错提示
        if (err.response.data.type === 'application/json') {
          const fileReader = new FileReader();
          fileReader.readAsText(err.response.data, 'utf-8');
          fileReader.onload = function () {
            const result = JSON.parse(fileReader.result);
            console.log(result, 'result');
            this.$message.error(result.message);
          }.bind(this); // Bind `this` to the onload function
          return;
        }

        const content = err.data
        const blob = new Blob([content], {
          type: "application/octet-stream"
        }) //构造一个blob对象来处理数据
        // this.$message.error(err.response.message)
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    getsprFn(){
      getspr().then(res=>{
        console.log(res,"审批人")
        this.sprlist = res.map(item => ({
          value: item.nickName,
          label: item.nickName
        }));
      })
    },
    getdeptFn() {
      getdept().then(res => {
        console.log(res, "部门");
        this.options = [res[0]]; // 将根节点数据赋值给 options
        this.optionsSq = [res[0]]
        // this.processTree(this.options); // 处理数据
      });
    },
    // processTree(nodes, level = 1) {
    //   nodes.forEach(node => {
    //     console.log(node,"node")
    //     // 如果节点的层级小于 3，禁用当前节点
    //     if (level < 3) {
    //       node.isDisabled = true;
    //       console.log(node.isDisabled,"node.isDisabled")
    //       if (node.children) {
    //         // 如果节点有子节点，递归处理
    //         this.processTree(node.children, level + 1);
    //       }
    //     } else {
    //       // 如果节点的层级是 3，允许选择
    //       node.isDisabled = false;
    //     }
    //   });
    // },
    handleInput(value) {
      // 处理选中值
      this.selectedId = value;
      const selectedNode = this.findNodeById(this.options, value);
      this.selectedLabel = selectedNode ? selectedNode.label : '';
      console.log(this.selectedLabel, "this.selectedLabel")
      console.log(selectedNode,'selectedNode1')
    },
    handleInputSq(value) {
      // 处理选中值
      this.selectedIdSq = value;
      console.log(this.selectedIdSq, "this.selectedIdSq")
      const selectedNode = this.findNodeById(this.optionsSq, value);
      this.selectedLabelSq = selectedNode ? selectedNode.label : '';
      console.log(this.selectedLabelSq, "this.selectedLabelSq")
    },
    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) return node;
        if (node.children) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },
    handleSelectionChange(val) {
      this.deptCurrent = val;
    },
    handleSelSprChange(val) {
      this.sprCurrent = val;
    },
    subDeptHandle() {
      // this.ruleForm.dataDept = this.deptCurrent.name;
      this.deptDialog = false;
    },
    closeHandle() {
      this.sprDialog = false;
      this.deptDialog = false;
      this.currentPage = 1;
      this.pageSize = 10;
      this.totalNum = 0;
      this.deptList = [];
      this.deptCurrent = "";
      this.sprCurrent = "";
      this.personalList = [];
    },
    subSprHandle() {
      this.ruleForm.spr = this.sprCurrent.name;
      this.sprDialog = false;
    },
    sprSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getPersonalList();
    },
    sprCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getPersonalList();
    },
    chooseSpr() {
      this.sprDialog = true
      this.getPersonalList()
    },
    getPersonalList() {
      let param = {
        pageSize:this.pageSize,
        pageNo:this.currentPage,
      }
      getSpUser(param).then((res) => {
        console.log(res)
        if(res.msg === '请登录') {
          this.$message({
            message: res.msg,
            type: "warning",
          });
          this.$router.push('/login')
          return
        }
        if(res.pageResult.content && res.pageResult.content.length > 0) {
          this.personalList = res.pageResult.content;
          this.totalNum = res.total;
          this.currentPage = res.current;
        }
      })
    },
    sizeChange(val) {
      this.pageSize = val
      this.getDepts()
    },
    currentChange(val) {
      this.currentPage = val;
      this.getDepts()
    },
    chooseDept() {
      this.deptDialog = true
      this.getDepts()
    },
    getDepts() {
      let param = {
        current:this.currentPage,
        size:this.pageSize,
        deptType:'0'
      }
      getDept(param).then((res)=>{
        console.log(res)
        if(res.pageResult.content && res.pageResult.content.length > 0) {
          this.deptList = res.pageResult.content
          this.totalNum = res.total
          this.currentPage = res.current
          this.pageSize = res.size
        }
      })
    },
    getSqr() {
      if(Cookies.get('userInfo')){
        let sqrName = JSON.parse(Cookies.get("userInfo")).name
        this.ruleForm.sqr = sqrName;
        this.sqrFlag = true
      }
    },
    // 格式化日期方法，将 Date 对象转换为 "YYYY-MM-DD HH:mm:ss" 格式
    formatDate(date) {
      if (!date) return "";
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0");
      const day = d.getDate().toString().padStart(2, "0");
      const hours = d.getHours().toString().padStart(2, "0");
      const minutes = d.getMinutes().toString().padStart(2, "0");
      const seconds = d.getSeconds().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getCodeFn() {
      getCode().then((res) => {
        console.log(res, "yzm");
        this.codeUrl = res.img;
        this.ruleForm.uuid = res.uuid;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          const formattedRuleForm = {
            ...this.ruleForm,
            // startTime: this.formatDate(this.ruleForm.startTime),
            // endTime: this.formatDate(this.ruleForm.endTime),
            // dataDept:this.selectedLabel,
            appDept:this.parrment.dept ? this.parrment.dept.id : '' //申请部门的id
            // spr:this.parrment.username
          };
          subXqData(formattedRuleForm).then((res) => {
            console.log(res, "res");
            this.$message({
              message: res,
              type: "success",
            });
            this.fileList = [];
            this.resetForm('ruleForm');
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getSqr();
    },
  },
};
</script>
<style scoped>
.lists-box {
  display: flex;
  justify-content: space-between;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #ededed;
}
  .lists-box .list_title {
    font-size: 18px;
    border-bottom: 2px solid #149bff;
  }
  .lists-box .list_title span {
    color: #149bff;
  }

.el-form-item /deep/ .el-form-item__content {
  display: flex;
}

.el-form-item .el-form-item__content .deptInp{
  flex: 3;
}
.el-form-item .el-form-item__content .deptBtn {
  flex: 1;
  magrin-left:20px;
  padding-left: 10px;
}

.demo-ruleForm {
  margin-top: 20px;
}
.login-code {
  float: right;
}
</style>
